<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="file" />
    <script src="./spark-md5.js"></script>
    <script>
      document.title = "hello world!";
      const inp = document.querySelector("input");
      inp.onchange = async (e) => {
        const file = inp.files[0];
        if (!file) {
          return;
        }

        const chunks = createChunks(file, 10 * 1024);
        hash(chunks);
        let result =await hashAsync(chunks)
        console.log(result)
      };
      // 对文件进行分片
      function createChunks(file, chunkSize) {
        let result = [];
        for (let i = 0; i < file.size; i += chunkSize) {
          result.push(file.slice(i, i + chunkSize));
        }
        return result;
      }

      //   文件hash算法，将任何数据---》压缩成固定长度的字符串，单向生成。  MD5---spark-MD5
      function hash(chunks) {
        const spark = new SparkMD5();
        function _read(i) {
          if (i >= chunks.length) {
            console.log(spark.end());
            return;
          }
          const blob = chunks[i];
          const reader = new FileReader();
          reader.onload = (e) => {
            const bytes = e.target.result;
            spark.append(bytes);
            _read(i + 1);
          };
          reader.readAsArrayBuffer(blob);
        }
        _read(0);
      }

      function hashAsync(chunks) {
        return new Promise((resolve,reject) => {
          const spark = new SparkMD5();
          function _read(i) {
            if (i >= chunks.length) {
             resolve(spark.end());
              return;
            }
            const blob = chunks[i];
            const reader = new FileReader();
            reader.onload = (e) => {
              const bytes = e.target.result;
              spark.append(bytes);
              _read(i + 1);
            };
            reader.readAsArrayBuffer(blob);
          }
          _read(0);
        });
      }
    </script>
  </body>
</html>
